package com.yy.controller.ForegroundController;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.yy.config.R;
import com.yy.domain.Account;
import com.yy.domain.User;
import com.yy.service.ForegroundService.IUserService;
import com.yy.utils.Mail;
import com.yy.utils.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.regex.Pattern;

/**
 * 前台用户信息模块
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private MailUtil mailUtil;
    @Autowired

    private static HashMap<String,String> VerificationCodeCache = new HashMap<>();
    @GetMapping("/outLogin")
    public R outLogin(String userId){
        System.out.println("当前状态：" + StpUtil.isLogin());
        Boolean loginStatus = userService.outLogin(userId);
        if (loginStatus){
            return R.fail("登出失败");
        }else {
            return R.ok("登出成功");
        }
    }
    /**
     * 获取用户输入的用户名与密码
     * @return 返回提示
     */
    @RequestMapping(value = "/toLogin",method = RequestMethod.GET)
    public Object toLogin(Account account){
        return userService.toLogin(account);
    }
    /**
     * 查询用户是否存在
     * @return 返回提示
     */
    @RequestMapping(value = "/queryUser",method = RequestMethod.GET)
    public Object queryUser(Account account){
        return userService.queryUser(account);
    }

    /**
     * 通过id获取用户的身份信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/selectUserById",method = RequestMethod.GET)
    public User selectUserById(Integer id){
        return userService.selectUserById(id);
    }

    /**
     * 通过id修改用户信息
     * @param user
     * @return
     */
    @RequestMapping(value = "/updateUserById",method = RequestMethod.POST)
    public int updateUserById(@RequestBody User user){
        return userService.updateUserById(user);
    }

    /**
     * 通过id查询用户发布商品总量
     * @param id
     * @return
     */
    @RequestMapping(value = "/selectCountById",method = RequestMethod.GET)
    public int selectCountById(Integer id){
        return userService.selectCountById(id);
    }

    /**
     * 通过id删除账户信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteUserById",method = RequestMethod.GET)
    public int deleteUserById(Integer id){
        return userService.deleteUserById(id);
    }

    /**
     * 重置用户账户信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/restAccountById",method = RequestMethod.GET)
    public int restAccountById(Integer id){
        return userService.restAccountById(id);
    }

    /**
     * 添加用户信息接口
     * @param user
     * @return
     */
    @RequestMapping(value = "/insertUserInfo",method = RequestMethod.POST)
    public String insertUserInfo(@RequestBody User user){
        return userService.insertUserInfo(user);
    }

    /**
     * 添加用户密码接口
     * @param account
     * @return
     */
    @RequestMapping(value = "/insertUserToAccount",method = RequestMethod.POST)
    public int insertUserToAccount(@RequestBody Account account){
        return userService.insertUserToAccount(account);
    }

    /**
     *查询用户购物车数量接口
     * @param id
     * @return
     */
    @RequestMapping(value = "/selectCartCountById",method = RequestMethod.GET)
    public int selectCartCountById(int id){
        return userService.selectCartCountById(id);
    }

    /**
     * 查询用户评论数量接口
     * @param id
     * @return
     */
    @RequestMapping(value = "/selectCommentById",method = RequestMethod.GET)
    public int selectCommentById(int id){
        return userService.selectCommentById(id);
    }

    /**
     * 通过id查询账户信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/selectAccountById",method = RequestMethod.GET)
    public Account selectAccountById(int id){
        return userService.selectAccountById(id);
    }
    /**
     * 发送重置密码验证码
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "/sendResetCode")
    public R sendResetCode(@RequestBody JSONObject jsonObject) {
            String email = jsonObject.getString("email");
        // 验证邮箱格式
        if (!isValidEmail(email)) {
            return R.fail("邮箱格式不正确");
        }
        // 检查用户是否存在
        User user = userService.findUserByEmail(email);
        if (user == null) {
            return R.fail("用户不存在");
        }

        String code = RandomUtil.randomString(6);

        // 保存token到数据库或缓存中，关联到用户
        VerificationCodeCache.put(code, user.getUsername());
        // 发送重置链接到用户邮箱
        // 这里假设有一个方法 sendEmail 用于发送邮件
        String emailContent = "您正在重置密码若非本人操作及时前往平台修改密码，您的验证码为：" + code;
        Mail mail = new Mail();
        mail.setRecipient(email); // 设置收件人
        mail.setSubject("集市交易平台"); // 设置邮件主题
        mail.setContent(emailContent); // 设置邮件内容
        mailUtil.sendSimpleMail(mail);
        return R.ok("验证码已发送到您的邮箱");
    }

    /**
     * 重置密码
     * @param code
     * @return
     */
    @GetMapping(value = "/resetPassword")
    public R resetPassword(@RequestParam String code) {
        String username = VerificationCodeCache.get(code);
        if (username == null) {
            return R.fail("验证码错误或已过期");
        }

        // 根据用户名查找用户
        Account user = userService.findUserByUsername(username);
        if (user == null) {
            return R.fail("用户不存在");
        }

        // 重置密码为默认值
        user.setPassword("$2a$10$3ujOwgfMHQoDGk9tUjaQo.eqME23A7TM8/BvlpMSX0sb9OWEkUd8a");
        user.setSalt("$2a$10$3ujOwgfMHQoDGk9tUjaQo.");
        // 假设存在加密工具类，这里注释掉的加密代码需要根据实际情况启用

        userService.updateUserAccountUser(user);
        // 重置成功后，移除 token
        VerificationCodeCache.remove(code);

        return R.ok("密码已重置为默认值");
    }

    // 验证邮箱格式
    private boolean isValidEmail(String email) {
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        Pattern pattern = Pattern.compile(emailRegex);
        return pattern.matcher(email).matches();
    }
}
